'use client';

import type { IPath, IQueryQqAuthUrlBody } from '@/interfaces';
import type { TBody, TMetadata } from '@/types';
import { type ChangeEvent, type FormEvent, useRef, useState } from 'react';
import useToast from '@/hooks/useToast';
import { useMutation } from '@tanstack/react-query';
import { queryQqAuthUrl } from '@/services/api';
import Link from 'next/link';
import { useTranslations } from 'use-intl';

export default function QqRegister({
  data,
  metadata,
}: {
  data: IPath;
  metadata: TMetadata;
}) {
  const t = useTranslations('RegisterPage');
  const [form, setForm] = useState({
    alias: '',
    isAgreeAgreement: false,
  });
  const [disableRegister, setDisableRegister] = useState(false);
  const agreementInputRef = useRef<HTMLInputElement>(null);
  const { show } = useToast();

  const queryQqAuthUrlMutation = useMutation(
    async (variables: TBody<IQueryQqAuthUrlBody>) => {
      return (await queryQqAuthUrl(variables)) as string;
    },
  );

  async function onSubmit(e: FormEvent<HTMLFormElement>) {
    e.preventDefault();
    e.stopPropagation();

    try {
      const { alias, isAgreeAgreement } = form;
      const qqConfig = data.qqConfig;
      if (!isAgreeAgreement) {
        agreementInputRef.current?.focus();
        show({
          type: 'DANGER',
          message: t('agreeBeforeRegister'),
        });
        return;
      }

      if (!qqConfig || !qqConfig.enable) {
        show({
          type: 'DANGER',
          message: t('tencentQQRegistrationDisabled'),
        });
        return;
      }

      const url = await queryQqAuthUrlMutation.mutateAsync({
        data: { alias },
      });
      setDisableRegister(true);

      show({
        message: t('enterTencentQQAuthorization'),
        type: 'PRIMARY',
      });

      setTimeout(() => {
        show({
          message: t('redirect'),
          type: 'PRIMARY',
        });
      }, 1000);

      setTimeout(() => {
        location.href = url;
      }, 1500);
    } catch (e) {
      queryQqAuthUrlMutation.reset();
      show({
        type: 'DANGER',
        message: e,
      });
    }
  }

  function onChangeForm(e: ChangeEvent<HTMLInputElement>) {
    const name = e.target.name;
    const value = e.target.value;

    if (name === 'agreement') {
      setForm({ ...form, isAgreeAgreement: !form.isAgreeAgreement });
    } else {
      setForm({ ...form, [name]: value.trim() });
    }
  }

  return (
    <form onSubmit={onSubmit}>
      <div className="my-3">
        <label className="form-label">{t('aliasOptional')}</label>
        <input
          value={form.alias}
          onChange={onChangeForm}
          name="alias"
          type="text"
          className="form-control"
          placeholder={t('enterAlias')}
          aria-describedby={t('enterAlias')}
        />
      </div>

      {data.qqConfig && data.qqConfig.enable ? (
        <div className="my-3">
          <button
            disabled={queryQqAuthUrlMutation.isLoading || disableRegister}
            type="submit"
            className="btn btn-outline-primary mt-4 mb-3 w-100"
          >
            {queryQqAuthUrlMutation.isLoading && (
              <span
                className="spinner-border spinner-border-sm me-2"
                role="status"
                aria-hidden="true"
              ></span>
            )}
            {disableRegister ? (
              <span>{t('redirect')}</span>
            ) : (
              <span>{t('quickRegistration')}</span>
            )}
          </button>
        </div>
      ) : (
        <div className="my-3">
          <button
            disabled
            type="submit"
            className="btn btn-outline-primary mt-4 mb-3 w-100"
          >
            {t('tencentQQRegistrationDisabled')}
          </button>
        </div>
      )}

      <div className="form-check my-3">
        <input
          ref={agreementInputRef}
          name="agreement"
          value="agreement"
          onChange={onChangeForm}
          type="checkbox"
          className="form-check-input cursor-pointer"
        />
        <label className="form-check-label user-select-none">
          <span>{t('readAndAgree')}</span>
          <Link href="/terms">{t('serviceAgreement')}</Link>
          <span>{t('and')}</span>
          <Link href="/privacy-policy">{t('privacyPolicy')}</Link>
        </label>
      </div>
    </form>
  );
}
